package com.wm.task2.dao;


import com.wm.task2.util.ManageFile;
import com.wm.task2.vo.Account;
import com.wm.task2.vo.Post;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


public class PostDAOFile {
    private String path = "D:/java/study/test/BBS/";


    public void addPost(String id, String title, String content) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dddd HH:mm:ss");
        Date now = new Date();
        String format = simpleDateFormat.format(now);

        String data = title + "\n" + content + "\n" + format + "\n";
        ManageFile.writerFile(path + id + ".txt", data, true);
    }

    public List<Post> myPost(String path) {
        List<Post> post = new ArrayList<>();
        Account account = new Account();
        String[] str = ManageFile.readFile(this.path + path).split("\n");
        int count = 0;
        for (int i = 0; i < str.length; i++) {
            if (i < 3) {
                account.setName(str[i++]);
                account.setAccountNum(str[i++]);
                account.setPassWord(str[i]);
                continue;
            } else {
                post.add(new Post());
                post.get(count).setAccount(account);
            }
            post.get(count).setTitle(str[i++]);
            post.get(count).setContent(str[i++]);
            post.get(count).setTime(str[i]);
            count++;
        }
        return post;
    }

    public List<List<Post>> allPost() {
        List<List<Post>> posts = new ArrayList<>();
        File dir = ManageFile.getFile(path);
        File[] files = dir.listFiles();
        for (File file : files) {
            String fileStr = file.toString();
            String[] filePath = fileStr.split("\\\\");
            if(filePath[filePath.length - 1].equals("id.txt")){
                continue;
            }
            posts.add(this.myPost(filePath[filePath.length - 1]));
        }
        return posts;

    }


}
